<template>
  <el-form
    :model="userForm"
    :rules="rules"
    ref="userFormRef"
    label-width="100px"
  >
    <el-form-item label="当前用户名">
      <span>{{ userInfo.username }}</span>
    </el-form-item>
    <el-form-item label="新的用户名" prop="username">
      <el-input v-model="userForm.username" clearable></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="modifyUser">立即修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      userForm: {
        username: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            validator(rule, value, callback) {
              //长度
              if (value.length < 2 || value.length > 8) {
                callback(new Error("请输入2-8位字符"));
              } else {
                //字符验证
                if (/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) {
                  callback(); //验证成功
                } else {
                  callback(new Error("只允许汉字、字母、下划线"));
                }
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    ...mapMutations(["updateUser"]),
    // 修改用户
    modifyUser() {
      this.$refs.userFormRef.validate(async (valid) => {
        if (valid) {
          let { data } = await this.$axios({
            method: "POST",
            url: "/personal/modifyUser",
            data: {
              username: this.userForm.username,
            },
          });
          if (data.code) return this.$message.error(data.message);
          //修改成功
          this.$message.success(data.message);
          this.updateUser(data.data);
          this.userForm.username = "";
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>